package com.shop.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.base.BaseApiService;
import com.shop.base.BaseResponse;
import com.shop.constants.Constants;
import com.shop.core.bean.TransformUtils;
import com.shop.mapper.UserMapper;
import com.shop.mapper.UserTokenMapper;
import com.shop.mapper.entity.User;
import com.shop.mapper.entity.UserToken;
import com.shop.member.inputDTO.UserLoginInputDTO;
import com.shop.member.outputtDTO.UserMessageDTO;
import com.shop.token.GenerateToken;
import com.shop.transaction.RedisDataSourceTransaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;

import java.util.ArrayList;
import java.util.List;


/**
 * Created with IntelliJ IDEA.
 * User: 王瑞文
 * Date: 2020/9/7
 * Time: 10:42
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GenerateToken generateToken;
    @Autowired
    private RedisDataSourceTransaction transaction;
    @Autowired
    private UserTokenMapper userTokenMapper;

    /**
     * 根据手机号查询用户信息
     *
     * @param phone
     * @return
     */
    public User selectByPhone(String phone) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("phone", phone));
    }

    /**
     * 根据ID查询用户信息
     *
     * @param id
     * @return
     */
    public User selectByID(String id) {
        return userMapper.selectById(id);
    }

    /**
     * 用户登陆信息判断
     *
     * @param phone
     * @param password
     * @return
     */
    public User userLogin(String phone, String password) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("phone", phone).eq("password", password));
    }

    /**
     * 生成token
     *
     * @return
     */
    public String CreatToken(User user, String type) {
        TransactionStatus transactionStatus = null;
      try{

          UserToken userToken = userTokenMapper.selectOne(new QueryWrapper<UserToken>().eq("user_id", user.getId())
                  .eq("login_type", type).eq("is_availability", "0"));
          transactionStatus = transaction.begin();
          System.out.println(userToken);
          if (userToken != null) {
              System.out.println("if1.0");
              //1、有活跃信息就先删除活跃信息
              String oldToken = userToken.getToken();
              generateToken.removeToken(oldToken);
              userToken.setIsAvailability(1);
              if (userTokenMapper.update(userToken, new QueryWrapper<UserToken>().eq("token", oldToken)) <= 0)
                  return "系统错误！";
          }
          String keyPrefix = Constants.MEMBER_TOKEN_KEYPREFIX + type;
          String token = generateToken.createToken(keyPrefix, user.getId().toString(), Constants.TOKEN_MEMBER_TIME);
          System.out.println(token);
          UserToken logonToken=new UserToken();
          logonToken.setToken(token);
          logonToken.setLoginType(type);
          logonToken.setUserId(user.getId());
          System.out.println("插入前"+logonToken);
          if (userTokenMapper.insert(logonToken)<=0){
              transaction.rollback(transactionStatus);
              return "数据库插入故障事务回滚";
          }
          transaction.commit(transactionStatus);
          return token;
      }catch (Exception e){
          try {
              transaction.rollback(transactionStatus);
              return "系统错误！";
          } catch (Exception ex) {
              ex.printStackTrace();
              return "系统错误";
          }
      }
    }

    /**
     * 修改用户信息
     *
     * @param id
     * @return
     */
    public BaseResponse<JSONObject> updateUserMessage(String id) {
        //TODO 方法好像有问题
        return null;
    }

    /**
     * 获取所有用户的信息
     *
     * @return
     */
    public BaseResponse<List<UserMessageDTO>> getAllUser(Integer page, Integer limit) {
        Page<User> currentPage = new Page<>(page,limit);
        IPage<User> z_userPages = userMapper.selectPage(currentPage, null);
        List<User> users = z_userPages.getRecords();
        ArrayList<UserMessageDTO> userMessageDTOS = new ArrayList<>();
        for (User u:users) {
            UserMessageDTO userMessageDTO = TransformUtils.doToDto(u, UserMessageDTO.class);
            userMessageDTOS.add(userMessageDTO);
            //System.out.println(userMessageDTO);
        }
        //users.forEach(System.out::println);
        return new BaseApiService<List<UserMessageDTO>>().setResultSuccess(userMessageDTOS);
    }

    /**
     * 删除用户根据id
     * @param id
     * @return
     */
    public BaseResponse<JSONObject> deleteUserById(String id) {
        int Id = Integer.parseInt(id);
        int result = userMapper.deleteById(Id);
        return new BaseApiService<JSONObject>().setResultSuccess();
    }
}
